package com.amkai.aes.webservice.binary.objecthandler;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.aescommon.service.binary.job.Job;
import com.amkai.aes.aescommon.service.result.AllSuperBillTypeResult;
import com.amkai.aes.generatedbeans.dictionary.Item;
import com.amkai.aes.generatedbeans.superbill.type.SuperBillType;
import com.amkai.aes.generatedbeans.superbill.type.SuperBillTypeGroup;
import com.amkai.aes.server.dictionary.SharedDictionaryManager;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class GetAllSuperBillTypeHandler implements JobObjectHandler {

	private static final Log log = LogFactory.getLog(GetAllSuperBillTypeHandler.class);

	
	@SuppressWarnings("unchecked")
	public Serializable process(Job job, Serializable object) throws Exception {
		AllSuperBillTypeResult ret = new AllSuperBillTypeResult();
		SessionManager sm = SiteManager.Start();
		sm.openSession();
		try {
			ret.getAllSB().addAll(sm.execute("from SuperBillType").list());
			// KKORNEL: AES-11533
			SharedDictionaryManager sdm = new SharedDictionaryManager(sm);
			for(SuperBillType sbt : ret.getAllSB()) {
				sbt.getName();
				for(SuperBillTypeGroup sbtg : sbt.getSuperBillTypeGroups()) {
					sbtg.getName();
					
					final boolean speedUp = false; // if true, then lesser table join to support mysql
					
					if (speedUp) {
						List<Long> itemIds = sm.execute("select sbtg.items.id from SuperBillTypeGroup sbtg where sbtg.id = :id")
						.setLong("id", sbtg.getId())
						.list();
						
						Set<Item> items = new HashSet<Item>();
						for(Long id : itemIds) {
							// KKORNEL: AES-11533
							Item item = sdm.loadItemAncestor(id);
							items.add(item);
						}
						
						sbtg.setItems(items);	
					} else {
						for(Item itm : sbtg.getItems()) {
							itm.getName();
						}
					}
					
				}
			}
		} catch ( Exception ex ) {
			sm.rollbackTransaction();
			log.error("",ex);
			throw ex;
		}finally {
			sm.closeSession();
		}
		return ret;
	}

}
